package main

import (
	"encoding/json"
	"fmt"
	"os"
	"path/filepath"
	"strings"
)

type Question struct {
	Question string   `json:"question"`
	Options  []string `json:"options"`
	Answer   string   `json:"answer"`
}

func RemoveChars(answer string, chars string) string {
	// 去除换行符
	answer = strings.ReplaceAll(answer, "\n", "")

	// 去除指定字符
	answer = strings.ReplaceAll(answer, chars, "")

	// 去除中间的空格
	answer = strings.ReplaceAll(answer, " ", "")

	return answer
}

func ExtractQuestions(html string) ([]Question, error) {
	var questions []Question

	lines := strings.Split(html, "<p></p>")
	for _, line := range lines {
		line = strings.TrimSpace(line)
		if line == "" {
			continue
		}

		parts := strings.Split(line, "</p>")
		if len(parts) < 2 {
			continue
		}

		tmp := strings.TrimPrefix(parts[0], "<p>")
		question := strings.TrimSpace(RemoveChars(tmp, "\n"))

		answer := RemoveChars(parts[len(parts)-2], "<p>答案：")
		options := parts[1 : len(parts)-2]
		for i, option := range options {
			options[i] = RemoveChars(option, "<p>")
		}

		questions = append(questions, Question{
			Question: question,
			Options:  options,
			Answer:   answer,
		})
	}

	return questions, nil
}

func SaveQuestionsToFile(questions []Question, filename string) error {
	data, err := json.MarshalIndent(questions, "", "  ")
	if err != nil {
		return err
	}

	err = os.WriteFile(filename, data, 0644)
	if err != nil {
		return err
	}

	return nil
}

func main() {
	dirs, _ := os.ReadDir("source")

	for _, childFile := range dirs {
		f := childFile.Name()

		fn := filepath.Join(`output`, strings.Split(f, ".")[0]+".json")
		file, _ := os.ReadFile(filepath.Join("source", f))

		questions, err := ExtractQuestions(string(file))
		if err != nil {
			fmt.Println("提取问题错误:", err)
			return
		}

		err = SaveQuestionsToFile(questions, fn)
		if err != nil {
			fmt.Println("保存问题到文件错误:", err)
			return
		}

		fmt.Println(childFile.Name() + "已成功保存到文件" + fn)
	}
}
